package com.maimao.kill.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.kill.client.UploadClient;
import com.maimao.kill.mapper.ActivityMapper;
import com.maimao.kill.mapper.ScheduleMapper;
import com.maimao.model.common.StatusInput;
import com.maimao.model.kill.Activity;
import com.maimao.model.kill.input.ActivitySaveEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.maimao.core.constant.Constants.ONE;
import static com.maimao.core.constant.Constants.ZERO;

/**
 * @author MaoLin Wang
 * @date 2021/4/7 10:25 上午
 */
@Service
@Slf4j
public class ActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private UploadClient uploadClient;

    private static final String[] FIELDS_ALL = new String[]{"id", "name", "url", "pic", "start_time", "end_time", "`status`", "create_time", "update_time", "create_user", "type"};
    private static final String[] FIELDS_SIMPLE = new String[]{"id", "name", "url", "pic", "start_time", "end_time", "`status`", "type"};

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void save(ActivitySaveEntity activity) {
        if (ObjectUtil.isNotEmpty(activity.getDeletePics())) {
            uploadClient.deleteBatch(activity.getDeletePics());
        }
        activityMapper.insert(activity);
    }

    /**
     * 获取进行中的活动列表
     */
    public List<Activity> processingActivity() {
        LocalDateTime now = DateUtils.now();
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<Activity>()
                .select(FIELDS_SIMPLE)
                .eq(Activity.FILED_STATUS, ONE)
                .lt(Activity.FILED_START_TIME, now)
                .gt(Activity.FILED_END_TIME, now);
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        return activities;
    }

    public List<Activity> all() {
        return activityMapper.selectAll();
    }


    /**
     * 更新活动信息
     */
    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public Result update(ActivitySaveEntity activity) {
        if (ObjectUtil.isNotEmpty(activity.getDeletePics())) {
            uploadClient.deleteBatch(activity.getDeletePics());
        }
        LocalDateTime now = DateUtils.now();
        Activity target = activityMapper.selectById(activity.getId());
        if (target == null) {
            return Result.notValid("当前活动不存在");
        }
        boolean started = target.getStartTime().compareTo(now) < 0;
        boolean end = target.getEndTime().compareTo(now) < 0;
        if (end) {
            return Result.fail("活动已结束");
        }
        if (started) {
            //已开始 只能修改结束时间
            activityMapper.updateById(Activity.builder().id(activity.getId()).endTime(activity.getEndTime()).updateTime(now).build());
            return Result.ok("活动已开始，只能修改结束时间");
        }
        activityMapper.updateById(activity);
        return Result.ok("更新成功");
    }

    /**
     * 开启或停止活动 会将相关的排期状态也一起修改
     */
    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void updateStatus(StatusInput statusInput) {
        Integer id = Convert.toInt(statusInput.getId());
        if (id == null) {
            log.error("id too long:{}", statusInput.getId());
            return;
        }
        //启用
        activityMapper.updateStatusById(statusInput.getStatus(), id);
        log.info("修改活动状态：{}--{}", id, statusInput.getStatus().equals(ONE) ? "开启" : "关闭");
        Integer enabled = 1;
        if (statusInput.getStatus().equals(ZERO)) {
            enabled = 0;
        }
        //更新排期状态
        scheduleMapper.updateEnabledByAcId(id, enabled);
    }
}
